package demo13;

public class Test {
    public static void main(String[] args) {

    }

    public int romanToInt(String s) {
        //获取s的长度，确定下标指向最后一个字符，依次往前读
        int index = s.length()-1;
        //将字符串转换成字符数组
        char[] chs = s.toCharArray();
        //定义存储结果
        int sum = 0;
        while(index != -1){

            switch (chs[index]){
                case 'I'://是1
                {
                    sum = sum + 1;
                    break;
                }
                case 'V':{
                    //是4或5
                    if(index != 0 && chs[index-1] == 'I'){
                        //是4
                        sum = sum + 4;
                        index --;
                    }else{
                        //是5
                        sum = sum + 5;
                    }
                    break;
                }
                case 'X':{
                    //是9或10
                    if(index != 0 && chs[index-1] == 'I'){
                        //是9
                        sum = sum + 9;
                        index --;
                    }else{
                        //是10
                        sum = sum + 10;
                    }
                    break;
                }
                case 'L':{
                    //是40或50
                    if(index != 0 && chs[index-1] == 'X'){
                        //是40
                        sum = sum + 40;
                        index --;
                    }else{
                        //是50
                        sum = sum + 50;
                    }
                    break;
                }
                case 'C':{
                    //是90或100
                    if(index != 0 && chs[index-1] == 'X'){
                        //是90
                        sum = sum + 90;
                        index --;
                    }else{
                        //是100
                        sum = sum + 100;
                    }
                    break;
                }
                case 'D':{
                    //是400或500
                    if(index != 0 && chs[index-1] == 'C'){
                        //是400
                        sum = sum + 400;
                        index --;
                    }else{
                        //是500
                        sum = sum + 500;
                    }
                    break;
                }
                case 'M':{
                    //是900或1000
                    if(index != 0 && chs[index-1] == 'C'){
                        //是900
                        sum = sum + 900;
                        index --;
                    }else{
                        //是1000
                        sum = sum + 1000;
                    }
                    break;
                }
            }
            //每次循环都让下标往左边移动，读取下一个字符
            index--;
        }
        return sum;
    }
}
